package com.example.mulittenantdemo.filter;

import cn.hutool.json.JSONUtil;
import com.auth0.jwt.interfaces.Claim;
import com.baomidou.dynamic.datasource.toolkit.DynamicDataSourceContextHolder;
import com.example.mulittenantdemo.util.JwtUtil;
import com.example.mulittenantdemo.util.Result;
import lombok.Data;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.StringUtils;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@ConfigurationProperties(prefix = "web")
@Component
@Data
public class TokenFilter implements Filter {

    List<String> excludePathPatterns =new ArrayList<>();
    private static final AntPathMatcher pathMatcher = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        String requestURI = httpRequest.getRequestURI();
        System.out.println("excludePathPatterns"+excludePathPatterns);
        if (!isExcludedPath(requestURI)) { // 忽略对指定路径的Token检查
            String token = httpRequest.getHeader("Authorization");
            if(StringUtils.isEmpty(token)){
               //设置响应类型json

                response.setContentType("application/json; charset=UTF-8");
                response.getWriter().write(JSONUtil.toJsonStr(Result.failure("未登录",null)));
               return;
            }
            // 执行Token检查
            Map<String, Claim> stringClaimMap = JwtUtil.verifyToken(token);
            if(stringClaimMap ==null){
                response.setContentType("application/json; charset=UTF-8");
                response.getWriter().write(JSONUtil.toJsonStr(Result.failure("未登录",null)));
                return;
            }
            Claim id = stringClaimMap.get("id");
            Claim tenantId = stringClaimMap.get("tenantId");
            System.out.println("userid="+id.asLong());
            DynamicDataSourceContextHolder.push(tenantId.asString());
            chain.doFilter(request, response);
        } else {
            // 直接放行指定路径的请求，不进行Token检查
            chain.doFilter(request, response);
        }
    }
    private boolean isExcludedPath(String requestURI) {
        for (String pattern : excludePathPatterns) {
            if (pathMatcher.match(pattern, requestURI)) {
                return true;
            }
        }
        return false;
    }


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 可选：在过滤器初始化时进行一些设置
    }

    @Override
    public void destroy() {
        // 可选：在过滤器销毁时清理资源
    }
}
